package com.yiyi.util;

import com.yiyi.entity.Exam;
import com.yiyi.vo.ExamVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 试卷redis工具类
 *
 * @author yiyi
 * @date 2021/6/6
 */
@Service
public class ExamRedisUtil {

    @Autowired
    private RedisUtil redisUtil;
    /** 保存时间均为10分钟 */
    private static final long TIME = 600;
    /** redis key 前缀 */
    private static final String KEY = "ydgm:exam:";

    /**
     * 判断redis是否存在该试卷对应的信息
     *
     * @param positionId    职位id
     * @return              是否存在该试卷对应的信息
     * */
    public boolean hasExam(String positionId) {
        boolean exam = redisUtil.hasKey(KEY + positionId);
        boolean list0 = redisUtil.hasKey(KEY + positionId + ":0");
        boolean list1 = redisUtil.hasKey(KEY + positionId + ":1");
        if (exam && list0 && list1) {
            return true;
        }
        return false;
    }

    /**
     * 保存试卷主体信息
     *
     * @param exam
     * */
    public void setExam(Exam exam) {
        String key = KEY + exam.getPositionId();
        redisUtil.hset(key, "examId", exam.getExamId(), TIME);
        redisUtil.hset(key, "examTitle", exam.getExamTitle(), TIME);
        redisUtil.hset(key, "examGrade", exam.getExamGrade() + "", TIME);
        redisUtil.hset(key, "examTime", exam.getExamTime() + "", TIME);
    }

    /**
     * 获取试卷主体信息，直接返回ExamVO
     *
     * @param positionId    职位id
     * @return              ExamVO
     * */
    public ExamVO getExam(String positionId) {
        ExamVO examVO = new ExamVO();
        String key = KEY + positionId;
        examVO.setExamId((String) redisUtil.hget(key, "examId"));
        examVO.setExamTitle((String) redisUtil.hget(key, "examTitle"));
        examVO.setExamGrade(Integer.valueOf((String) redisUtil.hget(key, "examGrade")));
        examVO.setExamTime(Integer.valueOf((String) redisUtil.hget(key, "examTime")));
        return examVO;
    }

    /**
     * 设置试卷题目id列表
     *
     * @param positionId    职位id
     * @param type          题目类型，0选择题，1简答题
     * @param ids           题目id列表，字符串格式
     * */
    public void setList(String positionId, int type, List<String> ids) {
        String key = KEY + positionId + ":" + type;
        for (String id : ids) {
            redisUtil.lSet(key, id, TIME);
        }
    }

    /**
     * 获取试卷题目列表
     *
     * @param positionId    职位id
     * @param type          题目类型，0选择题，1简答题
     * @return              题目id列表，字符串格式
     * */
    public List<String> getList(String positionId, int type) {
        String key = KEY + positionId + ":" + type;
        List<String> ids = redisUtil.lGet(key, 0, -1);
        return ids;
    }
}